package com.molihub.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @ClassName: IntelligentQuestionAnswer
 * @Description: 智能问答类
 * @author: GGBOY
 * @date 2020/1/19 16:09
 * @Version: 1.0
 **/
public class IntelligentQuestionAnswer {
    public static void main(String[] args) {
        queryAnswer("java学习路线");
    }
    public static void queryAnswer(String text) {
        String result = "";
        // 获得access_token
        String accessToken = AuthService.getAuth();
        String url = "https://aip.baidubce.com/rpc/2.0/kg/v1/cognitive/entity_annotation?access_token=" + accessToken;
        System.out.println(url);
        // 封装成json数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", text);
        // 建立POST请求
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {

            // 设置请求头
            httpPost.setHeader("Content-type", "application/json");
            //装填参数
            StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
            httpPost.setEntity(s);

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = httpclient.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                String body = EntityUtils.toString(entity, "UTF-8");
                JSONObject json = JSONObject.parseObject(body);
                JSONArray entity_annotation = json.getJSONArray("entity_annotation");
                for (Object js:
                     entity_annotation) {
                    System.out.println(js.toString());
                }
            }
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpPost.abort();
        }
    }
}
